package com.feiyu.queue;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class NewTask {

	private static final String QUEUE_NAME = "task";

	public static void send(byte taskSpendSeconds) {
		ConnectionFactory factory = new ConnectionFactory();
		// 连接的RabbitMQ节点
		factory.setHost("localhost");
		// ConnectionFactory抽象出了套接字连接Connection，并处理了协议版本协商和身份认证
		try (Connection connection = factory.newConnection();
		     Channel channel = connection.createChannel()) {
			// 发送前，必须声明一个队列
			// 声明是幂等的，只有当队列不存在时才会创建
			channel.queueDeclare(QUEUE_NAME, false, false, false, null);
			// 将消息发布到队列，消息是字节数组，因此可以为任意内容
			channel.basicPublish("", QUEUE_NAME, null, new byte[]{taskSpendSeconds});
			System.out.println(" [x] 发送任务，任务难度 " + taskSpendSeconds + " 秒");
		} catch (IOException | TimeoutException e) {
			e.printStackTrace();
		}
	}
}
